#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

typedef struct {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}pthread_lock;

int food = 0;

void* pthread_produce(void* arg){

    pthread_lock* lock = (pthread_lock *)arg;

    sleep(3);
    while(1){
        sleep(1);
        pthread_mutex_lock(&lock->mutex);

        printf("正在生产食物...\n");
        food++;
        printf("生产食物完毕...目前的食物总数:%d\n", food);

        pthread_mutex_unlock(&lock->mutex);

        pthread_cond_signal(&lock->cond);
    }

}


void* pthread_customer(void* arg){

    pthread_lock* lock = (pthread_lock *)arg;

    while(1){
        sleep(1);
        pthread_mutex_lock(&lock->mutex);
        pthread_cond_wait(&lock->cond,&lock->mutex);

        printf("正在消耗食物...\n");
        food--;
        printf("消耗食物完毕...目前的食物总数:%d\n", food);

        pthread_mutex_unlock(&lock->mutex);
    }
    
}


int main(int argc, char const *argv[])
{
    pthread_t pthread = -1;
    pthread_t pthread2 = -1;

    pthread_lock lock;

    pthread_mutex_init(&lock.mutex,NULL);
    pthread_cond_init(&lock.cond,NULL);
    int ret = 0;
    ret = pthread_create(&pthread, NULL, pthread_produce, &lock); //创建新的线程
    if (ret != 0){
        printf("pthread_create failed\n");
        return -1;
    }

    ret = pthread_create(&pthread2, NULL, pthread_customer, &lock); //创建新的线程
    if (ret != 0){
        printf("pthread_create failed\n");
        return -1;
    }

    printf("hello world!\n");
    pthread_join(pthread, NULL); //阻塞等待指定线程的退出
    pthread_join(pthread2, NULL); //阻塞等待指定线程的退出
    return 0;
}
